<?php

namespace app\index\controller;

use app\admin\model\Admin;
use app\admin\model\Aivideo;
use app\admin\model\SellerCode;
use app\admin\model\Card;
use app\admin\model\SellerLog;
use app\admin\model\StoreShop;
use app\common\controller\AliVod;
use app\common\controller\Frontend;
use Douyin\Open\ApiException;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Vod\V20180717\Models\DeleteMediaRequest;
use think\Request;
use app\admin\model\Videotask;
use \app\admin\model\User;
use Douyin\Open\Api\VideoPublishApi;
use Douyin\Open\Api\UserInfoApi;
use Douyin\Open\Model\VideoCreateBody;
use think\Session;
use think\Log;
use think\Cache;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Vod\V20180717\VodClient;
use TencentCloud\Vod\V20180717\Models\ComposeMediaRequest;
use app\admin\model\AivideoNumsLog;
use app\admin\model\AivideoCompositeLog;
use think\Db;
use app\admin\model\Activity;
use think\Validate;


class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    protected $ClientKey;
    protected $ClientSecret;


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->ClientKey = config('site.ClientKey');
        $this->ClientSecret = config('site.ClientSecret');
    }

    public function index()
    {
        return $this->view->fetch();
    }


    public function turntable($ids = null, $activityid = null, $videoid = null)//$ids为大转盘id,videoid视频id
    {

        $baseurl = $this->request->baseFile(true);
        $redirect_url = $baseurl . "/index/index/mycard/ids/{$activityid}";


        $videodata = Aivideo::where('id', $videoid)->find();


        $user_id = Session::get('user')['user_id'];
        $m_seller = new SellerCode();
        $cardscount = $m_seller->where(['user_id' => $user_id, 'activity_id' => $activityid])->where('status', '<>', 7)->count();
        $aivideos = Aivideo::where('activity_id', $activityid)->where('status', 2)->select();
        if ($aivideos) {
            $video_number = array_rand($aivideos, 1);
        }

        $local_user = Session::get('user');
        $access_token = $local_user['access_token'];
        $open_id = $local_user['open_id'];


        $model = new \app\admin\model\Activity;
        $row = $model->with(['card', 'manystoreshop'])
            ->find($activityid);


        if ($row->scan_times <= $cardscount) {
            $this->error('您已达到活动限制次数');
        }

        $turnInfo = Db::table('__TURNTABLE__')->where('id', $ids)->find();

        $idarrs[0] = $turnInfo['prize_one'];
        $idarrs[1] = $turnInfo['prize_two'];
        $idarrs[2] = $turnInfo['prize_three'];
        $idarrs[3] = $turnInfo['prize_four'];
        $idarrs[4] = $turnInfo['prize_five'];
        $idarrs[5] = $turnInfo['prize_six'];

        $prizedata = Db::table('__CARD__')->where('id', 'in', $idarrs)->select();


        $prizedata[0]['rate'] = $turnInfo['probability_one'];
        $prizedata[1]['rate'] = $turnInfo['probability_two'];
        $prizedata[2]['rate'] = $turnInfo['probability_three'];
        $prizedata[3]['rate'] = $turnInfo['probability_four'];
        $prizedata[4]['rate'] = $turnInfo['probability_five'];
        $prizedata[5]['rate'] = $turnInfo['probability_six'];


        $this->view->assign("row", $row);
        $this->view->assign("access_token", $access_token);
        $this->view->assign("open_id", $open_id);
        $this->view->assign("video", $videodata);
        $this->view->assign("prizedata", $prizedata);
        $this->view->assign("redirect_url", $redirect_url);


        return $this->view->fetch();
    }


    public function douyin($ids = null)
    {
        $activityInfo = Db::table('__ACTIVITY__')->where('id', $ids)->find();
        $nowTimestamp = time();
        if (!$activityInfo) {
            $this->error('没有找到该活动的相关信息');
        } else if ($nowTimestamp < $activityInfo['starttime']) {
            $this->error('活动未开始');
        } else if ($nowTimestamp > $activityInfo['endtime']) {
            $this->error('活动已结束');
        }

        $param = $this->request->param();

        if ($local_user = Session::get('user')) {

            $access_token = $local_user['access_token'];
            $open_id = $local_user['open_id'];
        } elseif (isset($param['access_token']) && isset($param['open_id'])) {

            $access_token = $param['access_token'];
            $open_id = $param['open_id'];
            $tmp_user = User::where('open_id', $open_id)->find();
            if ($tmp_user) {
                $tmp_user->open_token = $access_token;
                $tmp_user->save();
            }
        } else {
            if (empty($param['code'])) {
                $this->error("无授权code");
            }

            $code = $param['code'];
            $redirect_url = "https://open.douyin.com/oauth/access_token/?client_key={$this->ClientKey}&client_secret={$this->ClientSecret}&code={$code}&grant_type=authorization_code";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $redirect_url);//抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在

            //执行命令
            $data = curl_exec($ch);
            //关闭URL请求
            curl_close($ch);
            //显示获得的数据

            $data = json_decode($data, true);
            if ($data['data']['error_code'] == 0) {
                $access_token = $data['data']['access_token'];
                $open_id = $data['data']['open_id'];
            } else {
                if (!empty($data['data']['description'])) {
                    Log::error('获取access_token时发生错误：' . $data['data']['description'] . '【请求地址：' . $redirect_url . '】');
                    $this->error($data['data']['description']);
                }
            }
            $tmp_user = User::where('open_id', $open_id)->find();
            if ($tmp_user) {
                $tmp_user->open_token = $access_token;
                $tmp_user->save();
            }
        }
        /*  $open_id = "12574b18-f3c5-4af5-9d54-64af4db42d17";
          $access_token = 1;*/
        $aivideos = Aivideo::where('activity_id', $ids)->where('status', 2)->order('id', 'desc')->limit(20)->select();
        if ($aivideos) {
            foreach ($aivideos as $k => $v) {
                if (DIRECTORY_SEPARATOR === '\\') $v->local = trim($v->local, '/');
                if (!file_exists($v->local)) {
                    $v->status = 0;
                    $v->save();
                    unset($aivideos[$k]);
                }
                $aivideos[$k]->local = str_ireplace(ROOT_PATH . 'public', '', $aivideos[$k]->local);
            }
        }
        if (empty($aivideos)) $this->error("没有找到活动视频，请联系商家补充视频");
        $aivideos = array_slice($aivideos, 0, 3);

        $video_number = array_rand($aivideos);

        $model = new \app\admin\model\Activity;
        $row = $model->with(['card', 'manystoreshop'])
            ->find($ids);


        $user = User::where('open_id', $open_id)->find();
        if (!$user) {
            $apiInstance = new UserInfoApi();
            $result = $apiInstance->oauthUserinfoGet($access_token, $open_id);
            $user = new User();
            $user->group_id = 1;
            $user->username = $result['nickname'];
            $user->nickname = $result['nickname'];
            $user->avatar = $result['avatar'];
            $user->gender = $result['gender'];
            $user->open_id = $open_id;
            $user->open_token = $access_token;
            $user->jointime = time();
            $user->manystore_id = $row->manystore_id;
            $user->status = 'normal';
            $user->save();
        }

        $local_user = [
            'user_id' => $user->id,
            'open_id' => $open_id,
            'access_token' => $access_token,
        ];

        Session::set('user', $local_user);

        $tmp_selllog = SellerLog::where('user_id', $user->id)->where('activity_id', $ids)->where('video_id', $aivideos[$video_number]->id)->find();
        if (!$tmp_selllog) {


            if ($activityInfo['paytype'] != 2) {
                $tmp_selllog = new SellerLog();
                $tmp_selllog->user_id = $user->id;
                $tmp_selllog->activity_id = $ids;
                $tmp_selllog->video_id = $aivideos[$video_number]->id;
                $tmp_selllog->save();
            }


        }

        $baseurl = $this->request->baseFile(true);
        $redirect_url = $baseurl . "/index/index/mycard/ids/{$ids}";

        if ($row->redirect_type == 1 || $row->paytype == 1) {
            $store = StoreShop::where('id', $row->manystore_id)->find();
            $redirect_url = $store->douyin_url;

        } else if ($row->redirect_type == 2) {
            $redirect_url = $baseurl . "/index/index/mycard/ids/{$ids}";
        } elseif ($row->redirect_type == 3) {
            $redirect_url = $row->redirect_url;
        }


        if ($activityInfo['paytype'] == 2) {
            $bigturntableurl = $baseurl . "/index/index/turntable/activityid/{$ids}/ids/" . $activityInfo['turntable_id'] . "/videoid/" . $aivideos[$video_number]->id;


            header("Location: $bigturntableurl");

        }
        $aivideos[$video_number]->local = str_ireplace(ROOT_PATH . 'public', '', $aivideos[$video_number]->local);

        $this->view->assign("day", date('Y-n-j', ($row->card->day_times * 86400) + $row->card->createtime));
        $this->view->assign("row", $row);
        $this->view->assign("video", $aivideos[$video_number]);
        $this->view->assign("access_token", $access_token);
        $this->view->assign("open_id", $open_id);
        $this->view->assign("redirect_url", $redirect_url);
        $this->view->assign('videoData', $aivideos);


        /* try {
             $apiInstance=new VideoPublishApi();
             $result = $apiInstance->videoUploadPost($aivideos[2]->local, $open_id, $access_token);

             if($result->getData()->getVideo()->getVideoId())
             {
                 $video=$result->getData()->getVideo()->getVideoId();

           $re=$apiInstance->videoCreatePost($open_id, $access_token,(new VideoCreateBody(['video_id'=>$video])));
                 var_dump($re);exit;

             }
         } catch (ApiException $e) {
             echo 'Exception when calling VideoPublishApi->videoUploadPost: ', $e->getMessage(), PHP_EOL;
         }*/


        //}
        $baseurl = $this->request->baseFile(true);
        $mycard_url = $baseurl . "/index/index/mycard/ids/{$ids}";


        $this->view->assign("mycard_url", $mycard_url);


        return $this->view->fetch('douyin');


    }


    public function upload()
    {
        $param = $this->request->param();

        $aivideos = Aivideo::find($param['aivideo']);
        if (!file_exists($aivideos->local)) {
            $aivideos->status = 0;
            $aivideos->save();
            $this->error('无效的视频文件，请重新扫码');
        }

        //检查每个用户参与该活动最多次数
        $this->checkCardTimes();


        if ($param['cardid'] != 'cardid') {
            $user_id = Session::get('user')['user_id'];
            $tmp_selllog = new SellerLog();
            $tmp_selllog->user_id = $user_id;
            $tmp_selllog->activity_id = $param['ids'];
            $tmp_selllog->video_id = $param['aivideo'];
            $tmp_selllog->save();

        }

        //领取券码
        $open_id = $param['open_id'];
        $user = User::where('open_id', $open_id)->find();
        $m_seller = new SellerCode();
        $m_seller->user_id = $user->id;
        $m_seller->activity_id = $param['ids'];
        $m_seller->code = rand(111111, 999999);
        $m_seller->status = 7;
        $m_seller->card_id = $param['cardid'];
        $result = $m_seller->save();
        if (!$result) $this->error('保存数据时发生错误');
        $param['seller_code_id'] = $m_seller->id;


        $url = url('video_task', $param, false, true);
        $url = str_replace('https://', 'http://', $url);
        $result = asyncReq($url);
        if ($result['errCode'] === 0) {
            $this->success('已提交，约20秒领取完成');
        } else {
            $this->error('领取卡券时发生错误，请联系商家');
        }
    }


    public function mycard($ids)
    {

        $user_id = Session::get('user')['user_id'];

        $m_seller = new SellerCode();
        $m_Card = new Card();
        $model = new \app\admin\model\Activity;
        $cards = $m_seller->where(['user_id' => $user_id, 'status' => 0, 'activity_id' => $ids])->select();

        $Activitydata = $model->where('id', $ids)->find();


        //转盘卡卷
        if ($Activitydata->paytype == 2) {


            $cards = $m_seller->where(['user_id' => $user_id, 'status' => 0, 'activity_id' => $ids])->where('card_id', 'not null')->select();

            foreach ($cards as $key => $value) {
                $cards[$key]['card'] = $m_Card->where(['id' => $value['card_id']])->find();
                $cards[$key]['manystoreshop'] = StoreShop::where('id', $Activitydata->manystore_id)->find();
                $cards[$key]['day'] = date('Ymd', ($cards[$key]['card']->day_times * 86400) + $cards[$key]['card']->createtime);


            }

            $card_type = 2;
        } else {

            foreach ($cards as $card) {
                $row = $model->with(['card', 'manystoreshop'])
                    ->find($card->activity_id);
                $card->activity = $row;

                $card->day = date('Ymd', ($row->card->day_times * 86400) + $row->card->createtime);

            }
            $card_type = 1;

        }


        $this->view->assign("card_type", $card_type);
        $this->view->assign("row", $cards);
        return $this->view->fetch();

    }


    public function check($ids = null)
    {


        $model = new \app\admin\model\Activity;


        $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create&redirect_uri=http://www.ydk1.cn/index/index/douyin/ids/{$ids}";
        $row = $model->with(['card', 'manystoreshop'])
            ->find($ids);
        $this->view->assign("row", $row);
        $this->view->assign("url", $url);
        return $this->view->fetch();


    }

    public function seller($ids = null)
    {

        $param = $this->request->param();

        if ($local_user = Session::get('user')) {

            $access_token = $local_user['access_token'];
            $open_id = $local_user['open_id'];
        } elseif (isset($param['access_token']) && isset($param['open_id'])) {

            $access_token = $param['access_token'];
            $open_id = $param['open_id'];
            $tmp_user = User::where('open_id', $open_id)->find();
            if ($tmp_user) {
                $tmp_user->open_token = $access_token;
                $tmp_user->save();
            }
        } else {
            $code = $param['code'];
            $redirect_url = "https://open.douyin.com/oauth/access_token/?client_key={$this->ClientKey}&client_secret={$this->ClientSecret}&code={$code}&grant_type=authorization_code";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $redirect_url);//抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在

            //执行命令
            $data = curl_exec($ch);
            //关闭URL请求
            curl_close($ch);
            //显示获得的数据

            $data = json_decode($data, true);
            if ($data['data']['error_code'] == 0) {
                $access_token = $data['data']['access_token'];
                $open_id = $data['data']['open_id'];
            }
            $tmp_user = User::where('open_id', $open_id)->find();
            if ($tmp_user) {
                $tmp_user->open_token = $access_token;
                $tmp_user->save();
            }
        }
        $user = User::where('open_id', $open_id)->find();

        if (!$user) {
            $msg = "您还未领取过核销码";
            $this->view->assign("msg", $msg);
            return $this->view->fetch();
        }

        $where = array();
        $where['user_id'] = $user->id;
        $where['activity_id'] = $ids;
        $where['status'] = 0;
        $codeInfo = (new SellerCode())->where($where)->find();
        if (!$codeInfo) {
            $msg = "没有找到未使用的核销码";
            $result = 'fail';
        } else {
            $codeInfo->status = 1;
            $codeInfo->save();
            $msg = "已核销";
            $result = 'success';
        }

        $this->view->assign("msg", $msg);
        $this->view->assign("result", $result);
        return $this->view->fetch();
    }


    public function VideoTaskMixture()
    {
        $authInfo = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
        if (empty($authInfo['data']['authDouYinId'])) {
            Log::error('授权信息错误:authDouYinId');
            return false;
        }

        $VideotaskData = Videotask::where('admin_id', '>', 0)->order('id desc')->select();

        foreach ($VideotaskData as $key => $value) {

            $indexVideotask = Videotask::where('id', $value['id'])->lock(true)->find();
            $AivideoData = Aivideo::where('videotask_id', $indexVideotask->id)->count();

            $used_video_nums = AivideoCompositeLog::where('videotask_id', $indexVideotask->id)->sum('video_nums');


            if ($used_video_nums < $indexVideotask->Aivideo_nums_max) {


                if ($AivideoData < $indexVideotask->Aivideo_nums) {


                    $video_list = json_decode($indexVideotask['video_list']);


                    $audio_list = explode(',', $indexVideotask['audio_list']);
                    $back_music = $indexVideotask['back_music'];
                    $singleVideo_nums = min($indexVideotask['singleVideo_nums'], count($video_list)); //单个视频使用视频素材数
                    $singleAudio_nums = min($indexVideotask['singleAudio_nums'], count($audio_list));//使用音频素材数
                    $video_nums = $indexVideotask['video_nums'];//预生成视频数
                    $Aivideo_nums = $indexVideotask['Aivideo_nums'];//AI视频低于再预生成
                    $adminData = Admin::where('id', $indexVideotask['admin_id'])->find();

                    if ($adminData->last_aivideo_nums > $video_nums) {

                        $M_aivideo = new \app\admin\model\Aivideo();
                        $msg = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/video_quota?video_amount=' . $video_nums), true);

                        if ($msg['code'] == 0) return $msg['msg'];

                        $aivideo_data = [];
                        $tasks = [];
                        $taskIdData = [];


                        for ($nums = 0; $nums < $video_nums; $nums++) {

                            $video_list_temp = [];
                            for ($i = 0; $i < count($video_list); $i++) {
                                $arr = array_values($video_list[$i]);
                                $video_list_temp[$i] = $arr[array_rand($arr, 1)];
                            }

                            // file_put_contents('log.text', var_export( $video_list_temp, 1), FILE_APPEND);

                            shuffle($audio_list);
                            // $video_tmp = (array_slice(($video_list), 0, $singleVideo_nums));
                            $audio_tmp = (array_slice(($audio_list), 0, $singleAudio_nums));
                            $video_name = $indexVideotask['name'];
                            if (config('compose_vendor') === 'ali') {
                                $vod_return = (new AliVod)->compose($video_list_temp, $audio_tmp, $back_music, $video_name);
                                if (!empty($vod_return['task_id'])) $taskIdData[] = $vod_return['task_id'];
                            } else {
                                $vod_return = $this->general($video_list_temp, $audio_tmp, $back_music, $video_name);
                            }

                            $aitemp = [
                                'title' => $video_name,
                                'status' => $vod_return['status'],
                                'task_id' => $vod_return['task_id'],
                                'exception' => $vod_return['exception'],
                                'videotask_id' => $indexVideotask['id'],
                                'activity_id' => $indexVideotask['activity_id']
                            ];
                            //经过服务器中转

                            $tasks[] = $vod_return['task_id'];
                            $aivideo_data[] = $aitemp;
                        }

                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => 'http://zk.ydk1.cn/index.php/api/token/uptask',
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'POST',
                            CURLOPT_POSTFIELDS => array('taskid' => json_encode($tasks)),
                        ));

                        curl_exec($curl);
                        curl_close($curl);

                        if ($taskIdData) {
                            $res = AliVod::curl('http://zk.ydk1.cn/index.php/api/auth/mediaToAuthDouyin', ['taskIdData' => $taskIdData, 'authDouYinId' => $authInfo['authDouYinId']]);
                            $resData = json_decode($res, 1);
                            if (!isset($resData['code']) || $resData['code'] !== 1) {
                                if (empty($resData['msg'])) {
                                    Log::error('服务器保存数据失败');
                                } else {
                                    Log::error($resData['msg']);
                                }
                                return false;
                            }
                        }

                        Admin::where('id', $indexVideotask['admin_id'])->setInc('aivideo_nums', $video_nums);
                        Admin::where('id', $indexVideotask['admin_id'])->setDec('last_aivideo_nums', $video_nums);//扣除可用视频额度

                        //视频额度明细
                        AivideoNumsLog::create([
                            'admin_id' => $indexVideotask['admin_id'],
                            'type' => 2,
                            'aivideo_nums' => $video_nums,
                            'note' => '合成视频扣除视频额度',
                            'create_at' => date('Y-m-d H:i:s', time()),
                        ]);


                        //视频合成记录
                        AivideoCompositeLog::create([
                            'videotask_id' => $indexVideotask['id'],
                            'admin_id' => $indexVideotask['admin_id'],
                            'activity_id' => $indexVideotask['activity_id'],
                            'video_nums' => $video_nums,
                            'name' => $indexVideotask['name'],
                            'note' => '自动合成'
                        ]);


                        Log::write('测试自动生成视频');

                        $return = $M_aivideo->saveAll($aivideo_data);


                    }


                }


            }


        }


        // $this->success("添加AI处理视频成功");


    }


    public function general($videos, $audios, $back_music, $name)
    {
        if (!$config = Cache::get('cdk')) {
            $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
            if ($data_auth['code'] == 0) {
                $this->error($data_auth['msg']);
            }

            $config = $data_auth['data'];
            Cache::set('cdk', $config, 86400);
        }


        try {
            $cred = new Credential($config['SecretId'], $config['SecretKey']);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("vod.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new VodClient($cred, "", $clientProfile);
            $req = new ComposeMediaRequest();
            $video_template = [
                "VideoItem" => array(
                    "AudioOperations" => array(
                        array(
                            "VolumeParam" => array(
                                /* 1：视频音频静音 2：原声 */
                                "Mute" => 1
                            ),
                            /*Volume 需要操作音量 不操作音量为空*/
                            "Type" => "Volume"
                        )
                    ),
                    /*媒资库视频ID或媒资库url 不能使用对象存储url与第三方URL 需要该视频转码 目前使用转码是STD-H264-MP4-720P*/
                    "SourceMedia" => ""
                ),
                /*本素材类型：Video 视频 Audio ：音频轨道 Sticker ：贴图轨道*/
                "Type" => "Video"
            ];

            $audio_template = [
                "AudioItem" => array(
                    "AudioOperations" => array(
                        array(
                            "VolumeParam" => array(
                                "Gain" => 5
                            ),
                            "Type" => "Volume"
                        )
                    ),
                    "SourceMedia" => ""
                ),
                "Type" => "Audio"
            ];

            $params = array(
                "Tracks" => array(
                    /*视频轨道开始*/
                    array(
                        "TrackItems" => [],
                        "Type" => "Video"
                    ),
                    /*语音合成轨道开始*/
                    array(
                        "TrackItems" => [],
                        /*语音轨道定义该轨道为音频*/
                        "Type" => "Audio"
                    ),
                    /*背景音乐合成轨道开始*/
                    array(
                        "TrackItems" => array(
                            array(
                                "AudioItem" => array(
                                    "SourceMedia" => $back_music,
                                    /*截取时长为86秒  三个视频素材总时长=86秒*/
                                ),
                                "Type" => "Audio"
                            )
                        ),
                        "Type" => "Audio"
                    )
                ),
                "Output" => array(
                    /*输出文件名称与格式*/
                    "FileName" => $name,
                    "Container" => "mp4"
                ),


            );

            $videoItems = [];
            foreach ($videos as $video) {
                $video_template['VideoItem']['SourceMedia'] = $video;
                $videoItems[] = $video_template;
            }
            $audioItems = [];
            foreach ($audios as $audio) {
                $audio_template['AudioItem']['SourceMedia'] = $audio;
                $audioItems[] = $audio_template;
            }
            $params['Tracks'][0]['TrackItems'] = $videoItems;
            $params['Tracks'][1]['TrackItems'] = $audioItems;

            $req->fromJsonString(json_encode($params));
            $resp = $client->ComposeMedia($req);

            return ['status' => 1, 'task_id' => $resp->TaskId, 'exception' => ''];
        } catch (TencentCloudSDKException $e) {

            return ['status' => 0, 'task_id' => '', 'exception' => $e];
        }


    }

    //上传视频到抖音,并且为用户发布这个视频
    public function video_task()
    {
        ignore_user_abort(true);
        set_time_limit(600);

        $param = $this->request->param();

        //检查每个用户参与该活动最多次数
        $this->checkCardTimes();

        $access_token = $param['access_token'];
        $open_id = $param['open_id'];
        $user = User::where('open_id', $open_id)->find();
        $m_seller = new SellerCode();
        $aivideos = Aivideo::find(['id' => $param['aivideo']]);
        $activity = (new Activity())->find($param['ids']);
        $store = StoreShop::where('id', $activity->manystore_id)->find();
        $apiInstance = new VideoPublishApi();

        $result = $apiInstance->videoUploadPost($aivideos->local, $open_id, $access_token);
        if ($video = $result->getData()->getVideo()->getVideoId()) {
            $body = array();
            $body['video_id'] = $video;
            $body['text'] = mb_substr($aivideos->title, 0, 50);
            if ($store->poi_id) {
                $body['poi_id'] = $store->poi_id;
            }
            /*if ($store->address) {
                $body['text'] = $body['text'] . ',坐标' . $store->address;
            }*/
            if ($store->openid) {
                $body['at_users'] = [$store->openid];
                $body['text'] = $body['text'] . '@' . $store->name;
            }
            $re = $apiInstance->videoCreatePost($open_id, $access_token, (new VideoCreateBody($body)));

            //兼容客户填错信息
            if (empty($re['data']['item_id'])) {
                $body = array();
                $body['video_id'] = $video;
                $body['text'] = mb_substr($aivideos->title, 0, 50);
                if ($store->poi_id) {
                    $body['poi_id'] = $store->poi_id;
                }
                $re = $apiInstance->videoCreatePost($open_id, $access_token, (new VideoCreateBody($body)));
            }

            if (isset($re['data']['error_code']) && $re['data']['error_code'] === 0) {
                if (!$config = Cache::get('cdk')) {
                    $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
                    if ($data_auth['code'] == 0) {
                        Log::error(__LINE__ . $data_auth['msg']);
                    }

                    $config = $data_auth['data'];
                    Cache::set('cdk', $config, 86400);
                }
                if (!empty($aivideos->file_id)) {
                    try {
                        $cred = new Credential($config['SecretId'], $config['SecretKey']);
                        $httpProfile = new HttpProfile();
                        $httpProfile->setEndpoint("vod.tencentcloudapi.com");

                        $clientProfile = new ClientProfile();
                        $clientProfile->setHttpProfile($httpProfile);
                        $client = new VodClient($cred, "", $clientProfile);
                        $req = new DeleteMediaRequest();

                        $params = array(
                            "FileId" => $aivideos->file_id
                        );
                        $req->fromJsonString(json_encode($params));
                        $resp = $client->DeleteMedia($req);
                        $resData = json_decode($json = $resp->toJsonString(), true);
                        if (!isset($resData['RequestId'])) Log::error(__LINE__ . $json);
                    } catch (TencentCloudSDKException $e) {
                        Log::error(__LINE__ . $e->getMessage());
                    }

                    $unlink = @unlink($aivideos->local);
                    if (empty($unlink)) Log::error('发布视频后，删除视频文件失败：' . $aivideos->local);
                }
                $aivideos->delete();

                Db::startTrans();


                //保存券码状态
                $sellerCodeInfo = SellerCode::find($param['seller_code_id']);
                $result1 = false;
                if ($sellerCodeInfo) {
                    $sellerCodeInfo->status = 0;
                    $result1 = $sellerCodeInfo->save();
                }


                //写日志
                $tmp_selllog = SellerLog::where('user_id', $user->id)->where('activity_id', $aivideos->activity_id)->where('video_id', $param['aivideo'])->find();
                $tmp_selllog->video_code = $re['data']['item_id'];
                $tmp_selllog->type = 1;
                $result2 = $tmp_selllog->save();

                if ($result1 && $result2) {
                    Db::commit();
                } else {
                    Db::rollback();
                    Log::error(__LINE__ . '已上传并发布视频，但是保存数据时发生错误：' . serialize($result1) . PHP_EOL . serialize($result2));
                }
            } else {
                Log::error(__LINE__ . '为用户发布视频时发生错误：' . serialize($re));
            }
        } else {
            Log::error(__LINE__ . '上传视频到抖音时发生错误：' . serialize($result));
        }
    }

    //检查每个用户参与该活动最多次数
    private function checkCardTimes()
    {
        $param = $this->request->param();
        $param['seller_code_id'] = isset($param['seller_code_id']) ? $param['seller_code_id'] : 0;

        if ($param['cardid'] == 'cardid') {
            $user = User::where('open_id', $param['open_id'])->find();

            $scope = array();
            $scope['activity_id'] = $param['ids'];
            $scope['user_id'] = $user->id;
            $scope['id'] = array('<>', $param['seller_code_id']);

            //首先去掉【任务执行超时】的记录，超过3分钟为超时
            SellerCode::where($scope)->where('status', 7)->where('createtime', '<', time() - 180)->delete();

            //检查是否有正在进行中的领券任务
            $handlingSellerCodeCount = SellerCode::where($scope)->where('status', 7)->count();
            if ($handlingSellerCodeCount) {
                $this->error('您有正在处理的领券，请稍等一会重试');
            }

            $count = SellerCode::where($scope)->count();
            $activity = Activity::with('card')->find($param['ids']);
            if (!($count < $activity->card->use_times)) {
                $this->error('每个用户参与该活动最多 ' . $activity->card->use_times . ' 次');
            }
        }


    }

}
